<?php

require_once PATH_FFWD.'prototypes/view.clist.php';
require_once PATH_FFWD.'core/pagelistsmall.php';

class CListExView extends CListView{
	protected $pages='';
	protected $tdstylecache=Array();
	protected $e=0;
	public 		$table;
	protected $db=0;
	protected $overwritesettings=0;
	public 		$rowTemplateFn=0;
	public 		$headerTemplateFn=0;
	
	public function __construct(&$parent=NULL){		
		if(!$parent)throw new Exception('You MUST send module as first parameter to the view! (parent)');
		if($parent->table){
			$this->table=$parent->table;
			$this->e=$this->table->getByID('new');
		}
		parent::__construct($parent);
	}
	
	protected function renderResizer($k){
		echo '<div class="columnheadresizer" name="'.$k.'"></div>'."\n";
	}
	
	protected function getHTMLId(){
		return str_replace(Array('{','}','-'),'',$this->id);
	}
	
	protected function renderHead(&$resultset,$p){		
		if($this->headerTemplateFn){
			if(file_exists($this->headerTemplateFn)){
				echo '<thead>';
				include $this->headerTemplateFn;
				echo '</thead>';
				return;				
			}else{
				echo "file doesnt exist:".$this->headerTemplateFn;
				ob_start();
			}
		}
		$row=$resultset->fetch_assoc();
		if(isset($row['id']))unset($row['id']);
		$resultset->data_seek(0);
		echo '<tr class="tr" valign="bottom">'."\n";
			foreach($p['order'] as $k=>$v){
				if($v=='id')continue;				
				$s=$p['sortby']==$v;
			  echo '<td class="td columnhead'.($s?' active':'').'" name="'.$v.'" '.$this->getTDStyle($p,$v).'  href="';
			  echo link_for(NULL,Array("sortby"=>$v,"sortasc"=>($p["sortasc"]?0:1)));
			  //if(is_numeric($k))
			  $k=str_replace(' ','&nbsp;',translate($v));
			  if(strlen($k)>22)$k=substr($k,0,22).'. ';
			  if($s)$k.='<img src="'.LOCATION_ROOT.'/images/uiicons/'.($p["sortasc"]?'desc':'asc').'.png" />';
			  echo '">';
			  $this->renderResizer($v);			  
			  echo $k; 
			  echo '</td>'."\n";
			};		
		echo '</tr>'."\n";
		if($this->headerTemplateFn && !file_exists($this->headerTemplateFn)){
			file_put_contents($this->headerTemplateFn,ob_get_contents());
			ob_end_flush();
		}
	}
	
	protected function renderBody($resultset,$p){
		if($this->table){
			$pk=$this->table->getPrimaryKey();
		}else if($this->e){
			$pk=$this->e->getPrimaryKey()->name;
		}else{
			$pk='id';			
		};
		$st='';
		$resultset->data_seek(0);
		$i=0;
		if($this->rowTemplateFn && !file_exists($this->rowTemplateFn)){
			$tpl="<tr>\n";
			foreach($p['order'] as $k){
				$tpl.="	<td><?=\$row['$k'];?></td>\n";				
			}
			$tpl.="</tr>\n";		
			console_log('Template generated: '.$this->rowTemplateFn);
			file_put_contents($this->rowTemplateFn, $tpl);	
		};
		while($row=$resultset->fetch_assoc()){
			if($this->table){$st=$this->table->formatRow($row);};
			
			if($this->rowTemplateFn){
				include $this->rowTemplateFn;
				continue;
			}
			
			if(isset($p['rowclickcallback'])){
				echo '<tr class="tr" onclick=\''.($p['rowclickcallback']($row)).'\' '.$st.'>'."\n";
			}else{
				echo '<tr class="tr" href="'.link_for($row[$pk].'/'.$p[ACTION]).'" '.$st.'>'."\n";
			};
						
			foreach($p['order'] as $k){
				if($k=='id')continue;
				if(isset($row[$k])){						
					if(isset($p['limit']) && isset($p['limit'][$k]) && strlen($row[$k])>$p['limit'][$k]){
						$row[$k]=substr($row[$k],0,$p['limit'][$k]).'&#8230;';
					}
					echo '<td class="td" '.$this->getTDStyle($p,$k).'>'.
						str_replace(' ','&nbsp;',
							(isset($p['limit'][$k])?substr($row[$k],0,$p['limit'][$k]).(strlen($row[$k])>$p['limit'][$k]?'&hellip;':''):$row[$k]).
						' ').
						'</td>';
				}else{
					echo '<td  class="td" '.$this->getTDStyle($p,$k).'>&nbsp;</td>'."\n";
				};					
			};
			echo '</tr>'."\n";
			
			if(++$i==$this->pages->entryperpage)break;
		};
	}
	
	protected function getTDStyle(&$p,$key){
		if(isset($this->tdstylecache[$key])){
			return $this->tdstylecache[$key];
		}else{
			$st=Array();
			if(isset($p['colwidth']) && isset($p['colwidth']->$key)){
				if($p['colwidth']->$key<3)$st['display']='none';
				else
				$st['width']=$p['colwidth']->$key.'%';
			}
			if(isset($this->e) && isset($this->e->fields[$key]) && $this->e->fields[$key]->hidden)$st['display']='none';
			if(!count($st)){
				$this->tdstylecache[$key]='';
				return '';
			}
			$s='';
			foreach($st as $k=>$v)$s.=$k.':'.$v.';';
			
			if(isset($st['width'])){
				unset($st['width']);
				if(!count($st))$this->tdstylecache[$key]='';
				$this->tdstylecache[$key]='style="';
				foreach($st as $k=>$v)$this->tdstylecache[$key].=$k.':'.$v.';';
				$this->tdstylecache[$key].='"';				
			}else{
				$this->tdstylecache[$key]='style="'.$s.'"';
			}
			return 'style="'.$s.'"';
		}
	}
	
	public function resetSettings(){
		$this->overwritesettings=1;
	}
	
	protected function getColwidth(&$p){
		$p['colwidth']=$GLOBALS['user']->getSetting($this->id.':colwidth');
		if($p['colwidth'])$p['colwidth']=json_decode($p['colwidth']);
		if(!count($p['colwidth']) || $this->overwritesettings){		
			$p['colwidth']=new StdClass();
			foreach($p['fields'] as $k){
				$p['colwidth']->{(string)$k}=100/count($p['fields']);	
			};
			$GLOBALS['user']->setSetting($this->id.':colwidth',json_encode($p['colwidth']));				
		};
	}
	
	protected function getOrder(&$p){
		$p['order']=$GLOBALS['user']->getSetting($this->id.':fields');
		if($p['order']){
			$p['order']=json_decode($p['order']);
		};
		if(!is_array($p['order'])  || $this->overwritesettings){
			$p['order']=Array();			
			foreach($p['fields'] as $k){
				$p['order'][]=$k;	
			};
			$GLOBALS['user']->setSetting($this->id.':fields',json_encode($p['order']));				
		};		
	}
	
	protected function modifyQuery(&$query,&$p){
		$db=$this->table->getDB();
		if(isset($p['sortby'])){
			$query.=" ORDER BY ".$db->escape_string($p['sortby'])." ";
			if(!isset($p['sortasc']))$p['sortasc']=0;
			if(!$p['sortasc'])$query.=" DESC ";
		}
		
		$pp=Array();
		if(isset($_GET['page']))$pp['page']=(int)$_GET['page'];
		
		//-----determine number of rows!
	
		if(preg_match('/SELECT (.*) FROM .*/',$query,$match)){
			$qc=str_replace($match[1],'COUNT(*) as cnt',$query);
			$rs=$db->query($qc);
			$pp['numrows']=$rs->fetch_object()->cnt;			
		}else{
			$rs=$db->query($query);
			$pp['numrows']=$rs->num_rows;
		}
		
		//$pp['numrows']=$resultset->num_rows;
		//----------------	
		
		if(isset($p['entryperpage']))$pp['entryperpage']=$p['entryperpage'];		
		$this->pages=new PageListSmall($pp);		
		$query.=" LIMIT ".$this->pages->firstrecord.",".$this->pages->entryperpage." ";		
	}

	public function render($query,$p=Array()){
		global $app,$db;		
		$this->modifyQuery($query,$p);
		$resultset=$db->query($query);
		if(!$resultset){
			echo error_span( translate('QUERY_ERROR') );
		};
		if(!$resultset->num_rows)return;		
		if(!isset($p[ACTION]))$p[ACTION]='show';
		if(!isset($p['className']))$p['className']='clistex';
		if(!isset($p['nohead']))$p['nohead']=0;
		if(!isset($p['sortasc']))$p['sortasc']=0;
		if(isset($p['rowtplfn']))$this->rowTemplateFn=$p['rowtplfn'];
		$this->db=&$this->parent->getTable()->getDB();		
		if(!isset($p['order'])){
			$row=$resultset->fetch_assoc();
			$p['order']=Array();
			foreach($row as $k=>$v)$p['order'][$k]=$k;
			$resultset->data_seek(0);
		};
		if(!isset($p['sortby'])){
			$p['sortby']=NULL;			
		}					
		//$app->link('listexsearch','js');
		if(!isset($p['noframe'])){
			if(isset($p['maxheight']))echo '<div style="max-height:'.$p['maxheight'].'px;overflow:auto;border-left:1px dotted #999999;border-top:1px dotted #000000;border-bottom:1px dotted #000000;">';
			echo $this->pages;
			echo '<table class="'.$p['className'].'" cellpadding="0" cellspacing="0" id="'.$this->getHTMLId().'" width="100%" >';
			if(!$p['nohead']){		
				echo '<thead>';
				$this->renderHead($resultset,$p);
				echo '</thead>';
			}
			echo "<tbody>";
		}
		$this->renderBody($resultset,$p);				
		if(!isset($p['noframe'])){
			echo '</tbody>';
			echo '</table>';
			echo $this->pages;
			if(isset($p['maxheight']))echo '</div>';
		}else{
			echo "\n<script type='text/javascript'>INITHTMLCOMPONENTS();</script>";
		};
	}
}
